package com.dtsz.m2.ui.dashboard;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.android.volley.Request;
import com.bumptech.glide.Glide;
import com.cxy.library.entity.BannerEntity;
import com.cxy.library.iutils.IBannerBaseAdapter;
import com.cxy.library.view.BannerView;
import com.dtsz.m2.R;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.ui.activity.CommonProblemActivity;
import com.dtsz.m2.ui.activity.ForgetActivity;
import com.dtsz.m2.ui.activity.GameRoleActivity;
import com.dtsz.m2.ui.activity.InvitationNumberActivity;
import com.dtsz.m2.ui.activity.LoginActivity;
import com.dtsz.m2.ui.activity.MedalWallActivity;
import com.dtsz.m2.ui.activity.QrcodeActivity;
import com.dtsz.m2.ui.activity.TaskActivity;
import com.dtsz.m2.ui.base.BaseFragment;
import com.dtsz.m2.ui.model.HomeVo;
import com.dtsz.m2.ui.model.MwRecordVo;
import com.dtsz.m2.ui.model.Users;
import com.dtsz.m2.utils.StatusBarUtils;
import com.dtsz.m2.volley.state.HUCState;

import java.util.List;

public class MiningFragment extends BaseFragment {
    private BannerView bannerView;
    private TextView tvNum, tvNum1, tvH, tvYesSum, tvNoSum;
    private View llM2;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_mining, container, false);
        View rootBg = root.findViewById(R.id.ll_bg);
        if (rootBg != null) {
            rootBg.setPadding(0, StatusBarUtils.getStatusBarHeight(getActivity()), 0, 0);
        }
        StatusBarUtils.setTransparentStatusBar(getActivity());
        View view = root.findViewById(R.id.ll_show_end);
        bannerView = root.findViewById(R.id.id_bannerView);
        root.findViewById(R.id.ll_url).setOnClickListener(this);
        root.findViewById(R.id.ll_inv).setOnClickListener(this);
        root.findViewById(R.id.ll_identification).setOnClickListener(this);
        root.findViewById(R.id.ll_notice).setOnClickListener(this);
        root.findViewById(R.id.ll_xunzhang).setOnClickListener(this);
        root.findViewById(R.id.ll_game).setOnClickListener(this);
        tvNum = root.findViewById(R.id.tv_num);
        tvNum1 = root.findViewById(R.id.tv_num1);
        tvYesSum = root.findViewById(R.id.tv_yes_sum);
        tvYesSum.setOnClickListener(this);
        tvNoSum = root.findViewById(R.id.tv_no_sum);
        tvNoSum.setOnClickListener(this);
        tvH = root.findViewById(R.id.tv_h);
        llM2 = root.findViewById(R.id.ll_m2);
        ScaleAnimation scaleAnimation = (ScaleAnimation) AnimationUtils.loadAnimation(getActivity(), R.anim.scale);
        view.startAnimation(scaleAnimation);
        view.setOnClickListener(this);
        return root;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hucRequestInterfase.cancelAll();
    }

    @Override
    public void onStart() {
        super.onStart();
        initMining();
        initBanner();
    }

    @Override
    public void onErrorLogin(int inputType) {
        super.onErrorLogin(inputType);
        setSharedPreferences("tokenRSA", "token001");
        getActivity().finish();
        sendIntent(getActivity(), LoginActivity.class);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_url:
                initData();
                break;
            case R.id.ll_inv:
                sendIntent(getActivity(), InvitationNumberActivity.class);
                break;
            case R.id.ll_identification:
                sendIntent(getActivity(), CommonProblemActivity.class);
                break;
            case R.id.ll_xunzhang:
                sendIntent(getActivity(), MedalWallActivity.class);
                break;
            case R.id.ll_game:
                sendIntent(getActivity(), GameRoleActivity.class);
                break;
            case R.id.ll_notice:
                getTask();
                break;
            case R.id.tv_yes_sum://收币
                String yesSum = tvYesSum.getText().toString();
                if ("0.000".equals(yesSum)) {
                    showToast("暂无可收币");
                } else {
                    initReceivingCurrency();
                }
                break;
            case R.id.tv_no_sum:
                String noSum = tvNoSum.getText().toString();
                if ("0.000".equals(noSum)) {
                    showToast("请点击M2开始挖矿");
                } else {
                    showToast("正在开采中，暂不可收取");
                }
                break;
            case R.id.ll_show_end:
                int visiblity = llM2.getVisibility();
                if (visiblity == View.VISIBLE) {
                    initStart();
                } else {
                    sendIntent(getActivity(), ForgetActivity.class);
                }
                break;
        }
    }

    private void getTask() {
        //获取网络数据
        loading();
        pageVo.setLikeName("视频任务");
        hucRequestInterfase.executeStr(this, HomeVo.class,
                HUCState.HUC_REQEUST_CODE_6, Request.Method.POST, UrlConfig.VERSION_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_6:
                if (response instanceof HomeVo) {
                    HomeVo homeVo = (HomeVo) response;
                    if ("1".equals(homeVo.getState())) {//强制更新
                        sendIntent(getActivity(), TaskActivity.class);
                    } else {
                        showToast("暂未开放");
                    }
                }
                break;
            case HUCState.HUC_REQEUST_CODE_1:
                if (response instanceof Users) {
                    Users user = (Users) response;
                    Intent intentUrl = new Intent();
                    intentUrl.setClass(getActivity(), QrcodeActivity.class);
                    intentUrl.putExtra("URL", user.getBuQrcode());
                    intentUrl.putExtra("URLCode", user.getBuCode());
                    startActivity(intentUrl);
                } else {
                    Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
                }
                break;
            case HUCState.HUC_REQEUST_CODE_2:
                if (response instanceof HomeVo) {
                    HomeVo home = (HomeVo) response;
                    String num = home.getNumCount();
                    num = num.replace(".", ",");
                    String[] nums = num.split(",");
                    tvNum.setText(nums[0]);
                    tvNum1.setText(nums[1]);
                    tvYesSum.setText(home.getYesSum());
                    tvNoSum.setText(home.getNoSum());
                    if ("1".equals(home.getState())) {
                        tvH.setVisibility(View.VISIBLE);
                        llM2.setVisibility(View.GONE);
                        tvH.setText(home.getFormula());
                    }

                    startFlickStop(tvYesSum);

                }
                break;
            case HUCState.HUC_REQEUST_CODE_3:
                String strMsg = (String) response;
                if ("收取成功".equals(strMsg)) {
                    initMining();
                }
                showToast(strMsg);
                break;
            case HUCState.HUC_REQEUST_CODE_4:
                if (response instanceof HomeVo) {
                    HomeVo homeVo = (HomeVo) response;
                    if ("1".equals(homeVo.getIsMedal())) {
                        setMealdlAlert(homeVo);
                    }
                    initMining();
                }
                break;
            case HUCState.HUC_REQEUST_CODE_5:
                if (response instanceof List) {
                    List<BannerEntity> bannerEntityList = (List<BannerEntity>) response;
                    if (bannerEntityList != null && bannerEntityList.size() > 0) {
                        LoopPhotoAdapter loopPhotoAdapter = new LoopPhotoAdapter(getActivity(), bannerEntityList);
                        if (bannerEntityList.size() <= 1) {
                            bannerView.setRl_point_group(View.GONE);
                        }
                        bannerView.setVisibility(View.VISIBLE);
                        bannerView.setAdapter(loopPhotoAdapter);
                    } else {
                        bannerView.setVisibility(View.GONE);
                    }
                }
                break;
            case HUCState.HUC_REQEUST_CODE_7:
                String re = (String) response;
                if ("成功".equals(re)) {
                    alertDialog1.dismiss();
                    sendIntent(getActivity(), MedalWallActivity.class);
                } else {
                    showToast(re);
                }
                break;
        }
        loadDismiss();
    }

    class LoopPhotoAdapter implements IBannerBaseAdapter {
        Context context;
        List<BannerEntity> data;

        public LoopPhotoAdapter(Context context, List<BannerEntity> entities) {//构造方法
            this.context = context;
            data = entities;
        }

        @Override
        public void loadImage(String url, ImageView imageView) {//加载图片
            if (context != null) {
                Glide.with(context).load(url).into(imageView);
            }
        }

        @Override
        public int setItemCount() {//数据个数
            return data.size();
        }

        @Override
        public List<BannerEntity> setData() {//设置数据
            return data;
        }

        @Override
        public void onItemClick(int position) {//点击事件
            BannerEntity bannerEntity = data.get(position);
            String url = bannerEntity.getBarUrl();
            if (!"0".equals(url)) {
                sendUrl(url);
            }

        }
    }

    private void initData() {
        hucRequestInterfase.executeStr(this, Users.class,
                HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.USERS_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    private void initMining() {
        hucRequestInterfase.executeStr(this, HomeVo.class,
                HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.MINING2_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    private void initReceivingCurrency() {
        loading();
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.RECEIVINGCURRENCY_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    private void initStart() {
        loading();
        hucRequestInterfase.executeStr(this, HomeVo.class,
                HUCState.HUC_REQEUST_CODE_4, Request.Method.POST, UrlConfig.STARTMINING2_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    private void initBanner() {
        pageVo.setType("5");
        hucRequestInterfase.executeStr(this, BannerEntity.class,
                HUCState.HUC_REQEUST_CODE_5, Request.Method.POST, UrlConfig.BANNER_URL,
                hucParameInterfase.getRequestParameter(pageVo), false);
    }

    private void startFlickStop(TextView view) {
        String textView = view.getText().toString();
        if ("0.000".equals(textView)) {
            stopFlick(view);
        } else {
            startFlick(view);
        }
    }

    private void startFlick(View view) {
        if (null == view) {
            return;

        }
        Animation alphaAnimation = new AlphaAnimation(1, 0);

        alphaAnimation.setDuration(500);

        alphaAnimation.setInterpolator(new LinearInterpolator());

        alphaAnimation.setRepeatCount(Animation.INFINITE);

        alphaAnimation.setRepeatMode(Animation.REVERSE);

        view.startAnimation(alphaAnimation);
    }

    /**
     * 取消View闪烁效果
     */

    private void stopFlick(View view) {
        if (null == view) {
            return;
        }
        view.clearAnimation();
    }

    AlertDialog alertDialog1;


    private void setMealdlAlert(HomeVo homeVo) {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_mealdl_alert, null);
        ImageView tvImage = root.findViewById(R.id.tv_image);
        Glide.with(getActivity()).load(homeVo.getLightUrl()).into(tvImage);
        TextView tvName = root.findViewById(R.id.tv_name);
        tvName.setText(homeVo.getName());
        TextView tvNum = root.findViewById(R.id.tv_num);
        tvNum.setText("+" + homeVo.getReward() + "㎡");
        dialog.setView(root);
        root.findViewById(R.id.tv_del).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog1.dismiss();
            }
        });
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MwRecordVo mwRecordVo = new MwRecordVo();
                mwRecordVo.setToken(pageVo.getToken());
                mwRecordVo.setLanguage("1");
                mwRecordVo.setGrade(homeVo.getGrade());
                mwRecordVo.setType(homeVo.getType());
                updateStatus(mwRecordVo);
            }
        });
        alertDialog1 = dialog.create();
        alertDialog1.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog1.setCancelable(false);
        alertDialog1.show();
    }

    void updateStatus(MwRecordVo mwRecordVo) {
        loading();
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_7, Request.Method.POST, UrlConfig.UPDATESTATUS_URL,
                hucParameInterfase.getRequestParameter(mwRecordVo), false);
    }
}
